#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/pwm.h"
#include "esp_log.h"
#include "include/pwm_helper.h"
#include "include/task_helper.h"

int _period = 1000;
uint _pin_num[8], _duties[8];
int _channel_num = 0;

void pwm_helper::set_period(int period) {
    _period = period;
}

int pwm_helper::add_pwm(gpio_num_t pin_num, float duty) {
    _pin_num[_channel_num] = pin_num;
    _duties[_channel_num] = duty * _period;
    ++_channel_num;
    return _channel_num - 1;
}

void _pwm_init_task(void *args) {
    const char tag[] = "pwm init task";
    ESP_LOGI(tag, "pwm_init_task running...");
    int resp = pwm_init(_period, _duties, _channel_num, _pin_num);
    ESP_LOGI(tag, "called pwm_init(...), ret: %d", resp);
    resp = pwm_start();
    ESP_LOGI(tag, "called pwm_start(...), ret: %d", resp);
    ESP_LOGI(tag, "run pwm_init_task finished. min(0x%x) stack capacity last.", uxTaskGetStackHighWaterMark(nullptr));
    vTaskDelete(nullptr);
}

void pwm_helper::start_pwm_init_task() {
    TaskHandle_t *handle_pwm_init_task = nullptr;
    xTaskCreate(_pwm_init_task, "pwm init", 0x3A0, nullptr, PRIORITY_INIT_TASK, handle_pwm_init_task);
}